package com.kfm.base.reflect;

import java.lang.reflect.Constructor;

public class Demo03 {

    public static void main(String[] args) {
        Class<Student> studentClass = Student.class;

        try {
            // 通过反射创建对象. class对象.newInstance() 会调用类的无参构造器(有无参构造并且能够访问)
//            Student student = studentClass.newInstance();
            /*
             通过反射创建对象. class对象.getDeclaredConstructor().newInstance() 会调用类的无参构造器(有无参构造并且能够访问)
                如果无参构造是私有的, 那么需要先设置无参构造器的访问权限 setAccessible(true)
             */
//            Constructor<Student> declaredConstructor = studentClass.getDeclaredConstructor();
//            // 设置无参构造器的访问权限
//            declaredConstructor.setAccessible(true);

            Constructor<Student> declaredConstructor = studentClass.getDeclaredConstructor(String.class);
            // 设置无参构造器的访问权限
            declaredConstructor.setAccessible(true);

            Student student = declaredConstructor.newInstance("张三");
//            System.out.println(student.getName());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

